﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DurableObject : MonoBehaviour
{
    Creature _caster;
    Action<DurableObject, List<Creature>> _hitCallback;
    List<Creature> _hitList= new List<Creature>();
    float _duringTime;
    float _hitRate;
    Timer _timerHitRime;
    CapsuleCollider _collider;
    public void Init(Creature caster, float duringTime,float hitRate,int radius, Action<DurableObject,List<Creature>> hitCallback)
    {
        _caster = caster;
        _hitCallback = hitCallback;
        _duringTime = duringTime;
        _hitRate = hitRate;

        _collider=gameObject.GetComponent<CapsuleCollider>();
        _collider.radius = radius;
        _collider.isTrigger = true;
        _collider.enabled = true;

        var rig = gameObject.AddComponent<Rigidbody>();
        rig.useGravity = false;

        TimerMgr.GetInstance().CreateTimerAndStart(_duringTime, 1, onTimeEnd);
        _timerHitRime = TimerMgr.GetInstance().CreateTimerAndStart(_hitRate, -1, onHitRate);

    }

    private void onTimeEnd()
    {
        _timerHitRime.Stop();
        ResManager.GetInstance().Release(this.gameObject);
    }

    
    private void onHitRate()
    {

        _collider.enabled = true;
        Debug.Log("hit");
        MonoManager.GetInstance().StartCoroutine(onWaitAndHit());
    }

    private IEnumerator onWaitAndHit()
    {
        _collider.enabled = false;
        yield return new WaitForFixedUpdate();//等待物理关键帧更新后再执行，避免UPdate更新帧缺失
        onHitEnd();
    }

    private void onHitEnd()
    {
        
        Debug.Log("hitEnd");
        if (_hitCallback != null)
        {
            _hitCallback(this, _hitList);
        }
        _hitList.Clear();
    }

    private void OnTriggerEnter(Collider other)
    {
      
        var creature=other.gameObject.GetComponent<Creature>();
        if (creature == null) { return; }
        if (creature == _caster) { return; }
        if (!creature.CanBeAttack(_caster)) { return; }
        _hitList.Add(creature);
        foreach (var hit in _hitList)
        {
            Debug.Log(hit.Name);
        }
    }
}
